<template>
	<view class="edit-profile">
		<view class="form-group">
			<view class="form-item">
				<text class="label">头像</text>
				<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
					<text class="edit-text">点击更换</text>
				</button>
			</view>
			
			<view class="form-item">
				<text class="label">昵称</text>
				<view class="input-wrapper">
					<input 
						type="nickname" 
						class="nickname-input" 
						placeholder="请输入昵称" 
						v-model="userInfo.nickname"
						@blur="validateNickname"
					/>
				</view>
			</view>
			
			<view class="form-item">
				<text class="label">性别</text>
				<view class="gender-group">
					<view 
						class="gender-option" 
						:class="{'active': userInfo.gender === 1}"
						@click="userInfo.gender = 1"
					>
						<text class="gender-text">男</text>
					</view>
					<view 
						class="gender-option" 
						:class="{'active': userInfo.gender === 2}"
						@click="userInfo.gender = 2"
					>
						<text class="gender-text">女</text>
					</view>
					<view 
						class="gender-option" 
						:class="{'active': userInfo.gender === 0}"
						@click="userInfo.gender = 0"
					>
						<text class="gender-text">未设置</text>
					</view>
				</view>
			</view>
			
			<view class="form-item">
				<text class="label">年龄</text>
				<view class="input-wrapper">
					<input 
						type="number" 
						class="input" 
						placeholder="请输入年龄" 
						v-model="userInfo.age"
					/>
				</view>
			</view>
			
			<view class="form-item">
				<text class="label">糖尿病类型</text>
				<view class="select-wrapper" @click="showDiabetesTypePopup = true">
					<text class="select-text">{{ getDiabetesTypeName(userInfo.diabetesType) }}</text>
					<text class="select-arrow">></text>
				</view>
			</view>
		</view>
		
		<button class="save-btn" @click="saveUserInfo">保存</button>
		
		<!-- 糖尿病类型选择弹窗 -->
		<view class="popup-mask" v-if="showDiabetesTypePopup" @click="showDiabetesTypePopup = false"></view>
		<view class="popup" v-if="showDiabetesTypePopup">
			<view class="popup-header">
				<text class="popup-title">选择糖尿病类型</text>
				<text class="popup-close" @click="showDiabetesTypePopup = false">×</text>
			</view>
			<view class="popup-content">
				<view 
					class="popup-item" 
					v-for="item in diabetesTypes" 
					:key="item.value"
					@click="selectDiabetesType(item.value)"
				>
					<text class="popup-item-text">{{ item.label }}</text>
					<text class="popup-item-check" v-if="userInfo.diabetesType === item.value">✓</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { getUserInfo as getStoredUserInfo, getUserProfile, updateUserAvatar, updateUserNickname } from '../../common/utils/auth.js'
	import { updateUserInfo, updateAvatarToBackend, updateNicknameToBackend } from '../../common/api/user.js'
	
	// 用户信息
	const userInfo = reactive({
		nickname: '',
		avatar: '',
		gender: 0,
		age: '',
		diabetesType: 0
	})
	
	// 糖尿病类型选择弹窗
	const showDiabetesTypePopup = ref(false)
	
	// 糖尿病类型列表
	const diabetesTypes = [
		{ label: '未确诊', value: 0 },
		{ label: '1型糖尿病', value: 1 },
		{ label: '2型糖尿病', value: 2 },
		{ label: '妊娠糖尿病', value: 3 },
		{ label: '其他类型', value: 4 }
	]
	
	// 获取糖尿病类型名称
	const getDiabetesTypeName = (type) => {
		const found = diabetesTypes.find(item => item.value === type)
		return found ? found.label : '未确诊'
	}
	
	// 选择糖尿病类型
	const selectDiabetesType = (value) => {
		userInfo.diabetesType = value
		showDiabetesTypePopup.value = false
	}
	
	// 选择头像
	const onChooseAvatar = async (e) => {
		const avatarUrl = e.detail.avatarUrl
		console.log('选择的头像:', avatarUrl)
		
		try {
			// 显示加载提示
			uni.showLoading({
				title: '更新头像中...',
				mask: true
			})
			
			// 更新头像
			userInfo.avatar = avatarUrl
			
			// 更新本地存储
			updateUserAvatar(avatarUrl)
			
			// 尝试同步到后端
			try {
				await updateAvatarToBackend(avatarUrl)
				console.log('头像同步到后端成功')
			} catch (error) {
				console.error('头像同步到后端失败:', error)
				// 本地更新成功即可，后端同步失败不影响用户体验
			}
			
			uni.hideLoading()
			uni.showToast({
				title: '头像更新成功',
				icon: 'success'
			})
		} catch (error) {
			console.error('头像更新失败:', error)
			uni.hideLoading()
			uni.showToast({
				title: '头像更新失败',
				icon: 'none'
			})
		}
	}
	
	// 验证昵称
	const validateNickname = async () => {
		if (!userInfo.nickname.trim()) {
			uni.showToast({
				title: '昵称不能为空',
				icon: 'none'
			})
			return false
		}
		
		if (userInfo.nickname.length > 20) {
			uni.showToast({
				title: '昵称最多20个字符',
				icon: 'none'
			})
			userInfo.nickname = userInfo.nickname.substring(0, 20)
			return false
		}
		
		try {
			// 更新本地存储
			updateUserNickname(userInfo.nickname)
			
			// 尝试同步到后端
			try {
				await updateNicknameToBackend(userInfo.nickname)
				console.log('昵称同步到后端成功')
			} catch (error) {
				console.error('昵称同步到后端失败:', error)
				// 本地更新成功即可，后端同步失败不影响用户体验
			}
			
			return true
		} catch (error) {
			console.error('昵称保存失败:', error)
			return false
		}
	}
	
	// 保存用户信息
	const saveUserInfo = async () => {
		if (!validateNickname()) return
		
		try {
			uni.showLoading({
				title: '保存中...',
				mask: true
			})
			
			// 更新用户信息到后端
			await updateUserInfo({
				nickname: userInfo.nickname,
				avatar: userInfo.avatar,
				gender: userInfo.gender,
				age: userInfo.age ? parseInt(userInfo.age) : undefined,
				diabetesType: userInfo.diabetesType
			})
			
			uni.hideLoading()
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})
			
			// 返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} catch (error) {
			console.error('保存用户信息失败:', error)
			uni.hideLoading()
			uni.showToast({
				title: '保存失败，请重试',
				icon: 'none'
			})
		}
	}
	
	// 加载用户信息
	onLoad(() => {
		// 从本地存储获取用户信息
		const storedUserInfo = getStoredUserInfo()
		
		if (storedUserInfo) {
			// 更新本地数据
			userInfo.nickname = storedUserInfo.nickname || ''
			userInfo.avatar = storedUserInfo.avatar || ''
			userInfo.gender = storedUserInfo.gender !== undefined ? storedUserInfo.gender : 0
			userInfo.age = storedUserInfo.age || ''
			userInfo.diabetesType = storedUserInfo.diabetesType || 0
		} else {
			// 尝试从userProfile获取
			const userProfile = getUserProfile()
			if (userProfile) {
				userInfo.nickname = userProfile.nickName || ''
				userInfo.avatar = userProfile.avatarUrl || ''
				userInfo.gender = userProfile.gender !== undefined ? userProfile.gender : 0
			}
		}
	})
</script>

<style lang="scss">
	.edit-profile {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
		
		.form-group {
			background-color: #fff;
			margin-bottom: 20rpx;
			padding: 0 30rpx;
			
			.form-item {
				display: flex;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 1px solid #f0f0f0;
				
				&:last-child {
					border-bottom: none;
				}
				
				.label {
					width: 180rpx;
					font-size: 30rpx;
					color: #333;
				}
				
				.avatar-btn {
					background: none;
					padding: 0;
					margin: 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					
					&::after {
						border: none;
					}
					
					.avatar {
						width: 120rpx;
						height: 120rpx;
						border-radius: 50%;
						margin-bottom: 10rpx;
					}
					
					.edit-text {
						font-size: 24rpx;
						color: #8cc9a1;
					}
				}
				
				.input-wrapper {
					flex: 1;
					
					.nickname-input, .input {
						width: 100%;
						height: 70rpx;
						font-size: 28rpx;
						color: #333;
					}
				}
				
				.gender-group {
					display: flex;
					
					.gender-option {
						padding: 10rpx 30rpx;
						margin-right: 20rpx;
						border-radius: 30rpx;
						background-color: #f5f5f5;
						
						&.active {
							background-color: #8cc9a1;
							
							.gender-text {
								color: #fff;
							}
						}
						
						.gender-text {
							font-size: 26rpx;
							color: #666;
						}
					}
				}
				
				.select-wrapper {
					flex: 1;
					display: flex;
					justify-content: space-between;
					align-items: center;
					
					.select-text {
						font-size: 28rpx;
						color: #333;
					}
					
					.select-arrow {
						font-size: 28rpx;
						color: #ccc;
						transform: rotate(90deg);
					}
				}
			}
		}
		
		.save-btn {
			width: 90%;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			background-color: #8cc9a1;
			color: #fff;
			font-size: 32rpx;
			margin: 60rpx auto;
		}
		
		.popup-mask {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 100;
		}
		
		.popup {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			z-index: 101;
			border-radius: 20rpx 20rpx 0 0;
			
			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1px solid #f0f0f0;
				
				.popup-title {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}
				
				.popup-close {
					font-size: 40rpx;
					color: #999;
				}
			}
			
			.popup-content {
				max-height: 600rpx;
				overflow-y: auto;
				
				.popup-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					border-bottom: 1px solid #f0f0f0;
					
					.popup-item-text {
						font-size: 30rpx;
						color: #333;
					}
					
					.popup-item-check {
						font-size: 30rpx;
						color: #8cc9a1;
					}
				}
			}
		}
	}
</style> 